from odoo import api, fields, models
import requests, json


class DingtalkMessage(models.AbstractModel):
    _name = 'dingtalk.message'
    _inherit = 'dingtalk.base'

    def asyncsend(self, msg=None, **kwargs):
        """
        发送工作通知
        agent_id: 发送消息时使用的微应用的AgentID。
        userid_list: 接收者的userid列表，最大用户列表长度100。
        dept_id_list: 接收者的部门id列表，最大列表长度20。接收者是部门ID时，包括子部门下的所有用户
        to_all_user: 是否给发送企业全部用户
        msg: 消息
        """
        headers = {
            'Content-Type': 'application/json'
        }
        access_token = self.access_token()
        url = """https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={}""".format(
            access_token)
        params = {'agent_id': kwargs['agent_id'],
                  'to_all_user': kwargs['to_all_user'],
                  'msg': msg}
        if not kwargs['to_all_user']:
            if kwargs['userid_list']:
                params['userid_list'] = kwargs['userid_list']
            else:
                params['dept_id_list'] = kwargs['dept_id_list']
        response = requests.request('post', url, data=json.dumps(params), headers=headers)
        return json.loads(response.text)

    def upload_media(self, type=None, fname=None, fpath=None):
        headers = {
            'Content-Type': 'multipart/form-data'
        }
        access_token = self.access_token()
        url = """https://oapi.dingtalk.com/media/upload?access_token={}""".format(
            access_token)
        params = {'filename': 'media',
                  'type': type,
                  'media': fpath,
                  'Content-Type': 'multipart/form-data',
                  'filelength': '65535'}
        files = [
            ('', ('{}'.format(fname), open('{}'.format(fpath), 'rb'), 'application/octet-stream'))
        ]

        response = requests.request("POST", url, headers=headers, data=params, files=files)

        return json.loads(response.text)
